<script setup>
import { onMounted, onUpdated, ref, watch } from 'vue';

import { useAccessStore } from '@vben/stores';

import { Plus } from '@element-plus/icons-vue';
import { ElNotification } from 'element-plus';

import { imgUrl } from '#/UrlsConfig';

const props = defineProps({
  fileList: {
    type: Array,
    default: () => [],
  },
  fileType: {
    type: Array,
    default: () => ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'],
  },
  width: {
    type: String,
    default: '150px',
  },
  height: {
    type: String,
    default: '150px',
  },
  borderRadius: {
    type: String,
    default: '8px',
  },
  uploadData: {
    type: Object,
    default: () => ({ module: '' }),
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  limit: {
    type: Number,
    default: 10,
  },
  fileSize: {
    type: Number,
    default: 5,
  },
});
const emits = defineEmits(['handle-success', 'handle-remove']);
const accessStore = useAccessStore();
const uploadHeader = ref({
  authorization: 'authorization-text',
  tokenId: accessStore.accessToken,
});
const fileList1 = ref([]);
const dialogVisible = ref(false);
const viewImageUrl = ref('');

onUpdated(() => {
  nextTick(() => {
    const dom =
      document.querySelectorAll(
        '.upload-img .is-disabled .el-upload.el-upload--picture-card',
      ) || [];
    for (let i = 0; i < dom.length; i++) {
      // dom[i].remove();
      // dom[i].style.display = 'none';
    }
  });
});

onMounted(() => {
  nextTick(() => {
    const dom =
      document.querySelectorAll(
        '.upload-img .is-disabled .el-upload.el-upload--picture-card',
      ) || [];
    console.log(dom, 'dom');
    for (const element of dom) {
      // dom[i].remove();
      element.style.display = 'none';
    }
  });
});

watch(
  () => props.fileList,
  (newVal, oldVal) => {
    if (Array.isArray(newVal)) {
      fileList1.value = newVal?.map((item) => {
        return {
          ...item,
          name: item.fileName,
          url: imgUrl + item.fileUrl,
        };
      });
    }
  },
  {
    deep: true,
    immediate: true,
  },
);

const beforeUpload = (rawFile) => {
  const imgSize = rawFile.size / 1024 / 1024 < props.fileSize;
  console.log(props.fileType, rawFile.type);
  const imgType = props.fileType.includes(rawFile.type);
  if (!imgType)
    ElNotification({
      title: '温馨提示',
      message: '上传图片不符合所需的格式！',
      type: 'warning',
    });
  if (!imgSize)
    setTimeout(() => {
      ElNotification({
        title: '温馨提示',
        message: `上传图片大小不能超过 ${props.fileSize}M！`,
        type: 'warning',
      });
    }, 0);
  return imgType && imgSize;
};

const uploadSuccess = (response, file, fileList) => {
  if (!response) return;
  const imgList = fileList?.map((item) => {
    if (item?.response)
      return {
        originalFileName: item?.response
          ? item?.response?.data?.originalFileName
          : item.fileName,
        fileName: item?.response
          ? item?.response?.data?.fileName
          : item.fileUrl,
        // fileUrl: item?.response ? item?.response?.data?.fileName : item.fileUrl,
        uid: item.uid,
        status: item.status,
      };
    else return item;
  });
  emits('handle-success', imgList);
  ElNotification({
    title: '温馨提示',
    message: '图片上传成功！',
    type: 'success',
  });
};

const handleRemove = (file) => {
  // const info = {
  //     uid: file.uid,
  //     status: file.status,
  //     originalFileName: file?.response ? file?.response?.data?.originalFileName : file.fileName,
  //     fileName: file?.response ? file?.response?.data?.fileName : file.fileUrl,
  // }
  // emits('handle-remove', info)
  emits('handle-remove', fileList1.value);
};

// 图片
const imageTypes = ['gif', 'jpg', 'png', 'jpeg'];
const image = ref(false);
const pdf = ref(false);
const handlePictureCardPreview = (file) => {
  viewImageUrl.value = file.url;
  image.value = imageTypes.some((item) => file.url.includes(item));
  pdf.value = file.url.includes('.pdf');
  dialogVisible.value = true;
};

const uploadError = () => {
  ElNotification({
    title: '温馨提示',
    message: '图片上传失败，请您重新上传！',
    type: 'error',
  });
};

const handleExceed = () => {
  ElNotification({
    title: '温馨提示',
    message: `当前最多只能上传 ${props.limit} 张图片，请移除后上传！`,
    type: 'warning',
  });
};
</script>

<template>
  <div class="upload-img">
    <el-upload
      v-model:file-list="fileList1"
      :accept="fileType.join(',')"
      :before-upload="beforeUpload"
      :data="uploadData"
      :disabled="disabled"
      :headers="uploadHeader"
      :limit="limit"
      :multiple="true"
      :on-error="uploadError"
      :on-exceed="handleExceed"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="uploadSuccess"
      action="/energy-admin/common/uploadFile"
      list-type="picture-card"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <!-- <div class="el-upload__tip" v-if="showTip">
            请上传
            <template v-if="fileSize">
                大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
            </template>
            <template v-if="fileType">
                格式为 <b style="color: #f56c6c">{{ fileType }}</b>
            </template>
            的图片
        </div> -->

    <el-image-viewer
      v-if="dialogVisible && image"
      :url-list="[viewImageUrl]"
      @close="dialogVisible = false"
    />
    <!-- pdf -->
    <el-dialog
      v-if="dialogVisible && pdf"
      v-model="dialogVisible"
      @close="dialogVisible = false"
    >
      <object
        :data="viewImageUrl"
        height="600px"
        type="application/pdf"
        width="100%"
      >
        <p>
          抱歉，您的浏览器不支持查看PDF文件。您可以<a :href="viewImageUrl.pdf"
            >点击此处下载PDF文件</a
          >。
        </p>
      </object>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped></style>
